import { addQuotationApi, deleteQuotationApi, editQuotationApi } from "@/api/configCenter/quotationApproval";
import { Modal, message } from "ant-design-vue";
import { Ref, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
export default function OperationHook(state: { formState: Ref<QuotationApproval.Form[]>; loading: Ref<boolean>; init: () => void }) {
  const { formState, loading, init } = state;
  const submitHandle = (row: QuotationApproval.Form, index: number) => {
    const { id, minPrice, maxPrice, quotationApprovalId } = row;
    if (!quotationApprovalId) return message.error(`第${index + 1}行-审批人不能为空!`);
    if (!minPrice && minPrice !== 0) return message.error(`第${index + 1}行-最小值不能为空!`);
    if (!maxPrice && maxPrice !== 0) return message.error(`第${index + 1}行-最大值不能为空!`);
    let requestFn;
    const params: any = {
      minPrice,
      maxPrice,
      approvalUsers: quotationApprovalId.map((t: any) => {
        return {
          quotationApprovalId: id ? id : "",
          bizUserId: t
        };
      })
    };
    if (!id) requestFn = addQuotationApi;
    else {
      params.id = id;
      requestFn = editQuotationApi;
    }
    loading.value = true;
    return requestFn(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("操作成功!");
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const addHandle = () => {
    formState.value.push({
      id: "",
      minPrice: undefined,
      maxPrice: undefined,
      quotationApprovalId: []
    });
  };
  const deleteHandle = (row: QuotationApproval.Form, index: number) => {
    if (!row.id) {
      return formState.value.splice(index, 1);
    }
    Modal.confirm({
      title: "确认删除此项审批配置吗?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        return deleteQuotationApi({ id: row.id }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("删除成功!");
            init();
          }
        });
      }
    });
  };
  return {
    submitHandle,
    addHandle,
    deleteHandle
  };
}
